import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';
import Detail from './../IssueTicket/Detail';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ personal_issue_ticket, loading, global }) => ({
  personal_issue_ticket,
  global,
  loading: loading.models.personal_issue_ticket,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      personal_issue_ticket: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        personal_issue_ticket: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'personal_issue_ticket/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'personal_issue_ticket/changeLoaded',
          });
          dispatch({
            type: 'personal_issue_ticket/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'personal_issue_ticket/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'personal_issue_ticket/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'personal_issue_ticket/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      personal_issue_ticket: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>

          <FormItem label="巡检工单主题">
            {getFieldDecorator('title', {
              initialValue: searchParams.title,
            })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
          </FormItem>
          <FormItem label="设备编号">
            {getFieldDecorator('device_number', {
              initialValue: searchParams.device_number,
            })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
          </FormItem>
          <FormItem label="状态">
            {getFieldDecorator('status', {
              initialValue: searchParams.status,
            })(
              <Select style={{width:'100px'}}>
                {
                  [{id:'',value:'全部'} ,{id:'2',value:'处理中'},{id:'3',value:'已完成'}].map((item,index)=>{
                    return <Option key={index} value={item.id}>{item.value}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'personal_issue_ticket/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('发布新巡检工单成功');
        that.setState({
          addModal: false,
        });
        const {
          personal_issue_ticket: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      title:'',
      device_number:'',
      status:'',
      page: 1,
      per_page: 30,
    });
  };

  handleComplete = () => {
    console.log('this.CompleteForm.props.form.',this.CompleteForm.state.fileList.length)
    this.setState({ loading: true });
    const formValues = this.CompleteForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    let formData = new FormData();
    if(this.CompleteForm.state.length===0){
      message.error('处理图片必填')
      return
    }
    this.CompleteForm.state.fileList.forEach(file => {
      formData.append('process_files[]', file);
    })
    // for(let i=0;i<this.CompleteForm.state.fileList.length-1;i++){
    //   console.log('append',i)
    //   console.log(this.CompleteForm.state.fileList[i])
    //   formData.append("process_files[]", this.CompleteForm.state.fileList[i]);
    // }

    formData.append("process_result", formValues.process_result);
    const that = this;
    this.props.dispatch({
      type: `personal_issue_ticket/complete`,
      payload: {
        id: this.state.editRecord.id,
        formData: formData,

      },
      callback() {
        message.success('完成巡检工单成功');
        that.setState({
          completeModal: false,
          loading: false
        });
        const {
          personal_issue_ticket: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
    setTimeout(function() {
      that.setState({
        loading: false
      });
    },5000)
  };
  handleCancel = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `personal_issue_ticket/cancel`,
      payload: { id },
      callback: () => {
        message.success('取消受理巡检工单成功');
        const {
          personal_issue_ticket: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  render() {
    const that = this;
    const {
      personal_issue_ticket: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            personal_issue_ticket: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '工单编号',
        width: 150,
        frozen: true,
        key: 'number',
      },
      {
        name: '发布时间',
        key: 'created_at',
        width: 150,
      },
      {
        name: '发布人',
        width: 100,
        key: 'publisher_name',
      },
      {
        name: '工单主题',
        width: 150,
        key: 'title',
      },
      {
        name: '工单地址',
        width: 150,
        key: 'address',
      },
      {
        name: '设备编号',
        width: 100,
        key: 'device_number',
      },
      {
        name: '状态',
        key: 'status',
        width: 100,
        formatter: (event) => {
          switch (event.value) {
            case -1:
              return <p className={ 'table-danger table-status' }>已取消</p>;
            case 1:
              return <p className={ 'table-warm table-status' }>未受理</p>;
            case 2:
              return <p className={ 'table-process table-status' }>处理中</p>;
            case 3:
              return <p className={ 'table-success table-status' }>已完成</p>;
          }

        },
      },
      {
        name: '处理结果',
        width: 150,
        key: 'process_result',
      },
      {
        name: '操作',
        width: 340,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >工单详情
          </Button>
          {
            event.row.status !== 3 &&
            <Button
              className={'btn-green'}
              type="primary"
              size="small"
              icon="check"
              onClick={(e) => {
                that.setState({
                  editRecord: event.row,
                  completeModal: true,
                });
              }
              }
            >完成工单
            </Button>
          }
          {
            event.row.status!==3&&
            <Button
              type="danger"
              size="small"
              icon="delete"
              onClick={(e) => {
                confirm({
                  title: `确定要取消受理工单${event.row.number}吗?`,
                  content: '请谨慎操作！',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered: true,
                  maskClosable: true,
                  onOk() {
                    that.handleCancel(event.row.id);
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }
              }
            >取消受理工单
            </Button>

          }


        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>个人巡检工单</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'personal_issue_ticket/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.completeModal} modalClass="completeModal"
                                title={`完成工单 ${this.state.editRecord.number}`}/>}
        destroyOnClose
        visible={this.state.completeModal}
        centered
        onOk={this.handleComplete}
        className="completeModal"
        width={600}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ completeModal: false, editRecord: {} });
        }}
        confirmLoading={this.state.loading}
      >
        <AddOrEditUser
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.CompleteForm = inst}/>
      </Modal>
      <Drawer
        title={`${this.state.editRecord.number} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={700}
        visible={this.state.infoModal}
      >
        <Detail id={this.state.editRecord.id}></Detail>
      </Drawer>
    </div>;
  }
}

export default BasicList;
